<script setup>
import request from '@/utils/request';
import { showDefaultmsg, showErrorMsg, showSuccessMsg, showWarningMsg } from '@/utils/show-msg';
import { getFromLocalStorage } from '@/utils/store-data';
import { ElMessageBox } from 'element-plus';
import { onMounted } from 'vue';
import { ref } from 'vue';

// bugs: 
// 1. 文件上传后dialog不消失
// 2. 编辑按钮点不了

const BASE_URL ='http://localhost:9999'
const uploadAvatarURL = ref(`${BASE_URL}/file/uploadFile`)
const uploadHeaders = ref({ Authorization: `Bearer ${getFromLocalStorage('token')}`})

const tableData = ref([])
  // pagination
const pageNum  = ref(1)
const pageSize = ref(5)
const total    = ref(10)
  // query
const username = ref('')
const name     = ref('')
  // add or edit dialog
const formTitle     = ref('')
const dialogVisible = ref(false)
const form          = ref({})
const formRef       = ref(null)
const rules         = {
  username: [{ required: true, message: '请输入账号', trigger: 'blur' }, { min: 2, max: 20, message: '账号长度为2-20个字符', trigger: 'blur' }],
  phone   : [{ required: true, message: '请输入手机号', trigger: 'blur' }, { min: 11, max: 11, message: '手机号11位', trigger: 'blur' }],
  name    : [{ required: true, message: '请输入姓名', trigger: 'blur' }, { min: 2, max: 4, message: '请输入正确的姓名', trigger: 'blur' }],
  email   : [{ required: true, message: '请输入邮箱', trigger: 'blur' }],
  address : [{ required: true, message: '请输入地址', trigger: 'blur' }],
}
  // current user
const currentUser = getFromLocalStorage("current-user")
  // ids to del
  // [1,2,3,4,5]
const ids = ref([])

const getData = (newPageNum) => {
  if (newPageNum) pageNum.value = newPageNum
  request({
    url   : '/user/selectByPage',
    method: 'get',
    params: {
      pageNum : pageNum.value,
      pageSize: pageSize.value,
      username: username.value,
      name    : name.value
    }
  }).then(res => {
    tableData.value = res.data.records
    total.value     = res.data.total
  })
}

const resetQuery = () => {
  username.value = ''
  name.value     = ''
  getData()
}
const handleAdd = () => {
  formTitle.value     = '新增用户'
  form.value.role     = 'USER'
  dialogVisible.value = true
}

const handleCurrentChange = (newPageNum) => getData(newPageNum)

const handleDialogCancel = () => {
  form.value          = {}
  formTitle.value     = ''
  dialogVisible.value = false
}
const handleDialogSubmit = () => {
  formRef.value.validate(valid => {
    if (!valid) {
      showErrorMsg("请填写完整信息 再提交")
    } else {
      request({
        url   : form.value.id ? '/user/update': '/user/add',
        method: form.value.id ? 'PUT'         : 'POST',
        data  : form.value
      }).then(res => {
        if (res.code === '200') {
          showSuccessMsg("操作成功")
          getData(1)
          form.value          = {}
          dialogVisible.value = false
        } else {
          showErrorMsg(res.msg)
        }
      })
    }
  })
}

const handleEdit = (row) => {
  form.value          = JSON.parse(JSON.stringify(row))
  dialogVisible.value = true
}
const del = (id) => {
  ElMessageBox.confirm(
    '确定要删除吗',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText : '取消',
      type             : 'warning'
    }
  ).then(() => {
    request({
      url   : `/user/delete/${id}`,
      method: 'DELETE'
    }).then((res) => {
      if (res.code === '200') {
        showSuccessMsg("操作成功")
        getData(1)
      } else {
        showErrorMsg(res.msg)
      }
    })
  }).catch(() => {
    showDefaultmsg("取消删除")
  })
}
const handleSelectionChange = (rows) => ids.value = rows.map(e => e.id)
const delBatch              = () => {
  if (!ids.value.length) {
    showWarningMsg("请选择要删除的数据")
    return
  } else {
    ElMessageBox.confirm('您确认批量删除这些数据吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText : '取消',
      type             : 'warning'
    }).then(() => {
      request({
        url   : '/user/delete/batch',
        method: 'DELETE',
        data  : ids.value
      }).then((res) => {
        if (res.code === '200') {
          showSuccessMsg("操作成功"),
            getData(1)
        } else {
          showErrorMsg(res.msg)
        }
      })
    }).catch(() => showDefaultmsg("取消删除"))
  }
}
const exportData = () => {
  if(!ids.value.length){
    window.open(`${BASE_URL}/user/export?token=${getFromLocalStorage('token')}&username=${username}$name=${name}`)
  }else{
    // [1,2,3] => '1,2,3'
    let idsStr = ids.value.join(',')
    window.open(`${BASE_URL}/user/export?token=${getFromLocalStorage('token')}&ids=${idsStr}`)
  }
}
const handleImport = (response, file, fileList) => {
  if(response.code === '200'){
    showSuccessMsg("导入成功")
    getData(1)
  }else{
    showErrorMsg("导入失败")
  }
}
const handleAvatarUploadSuccess = (response, file, fileList) => form.value.avatar = response.data
onMounted(() => getData())
</script>

<template>
  <div class="content">
    <!-- query -->
    <div>
      <el-input style="width: 200px" placeholder="查询用户名" v-model="username"></el-input>
      <el-input style="width: 200px; margin: 0 5px" placeholder="查询姓名" v-model="name"></el-input>
      <el-button type="primary" @click="getData(1)">查询</el-button>
      <el-button type="info" @click="resetQuery">重置</el-button>
    </div>
    <!-- btn -->
    <div style="margin: 10px 0">
      <el-button type="primary" plain @click="handleAdd">新增</el-button>
      <el-button type="danger"  plain @click="delBatch"  >批量删除</el-button>
      <el-button type="info"    plain @click="exportData">批量导出</el-button>
      <el-upload style="display: inline-block; margin-left: 10px" :show-file-list="false" :action="`${BASE_URL}/user/import`" :headers="uploadHeaders" :on-success="handleImport">
        <el-button type="primary" plain>批量导入</el-button>
      </el-upload>
    </div>
    <!-- table -->
    <el-table :data="tableData" stripe :header-cell-style="{ backgroundColor: 'aliceblue', color: '#666' }" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column prop="id" label="序号" width="70" align="center"></el-table-column>
      <el-table-column prop="username" label="用户名"></el-table-column>
      <el-table-column prop="name" label="姓名"></el-table-column>
      <el-table-column prop="phone" label="手机号"></el-table-column>
      <el-table-column prop="email" label="邮箱"></el-table-column>
      <el-table-column prop="address" label="地址"></el-table-column>
      <el-table-column prop="role" label="角色"></el-table-column>
      <el-table-column label="头像">
        <template v-slot="scope">
          <div style="display: flex; align-items: center">
            <el-image style="width: 50px; height: 50px; border-radius: 50%" v-if="scope.row.avatar"
              :src="scope.row.avatar" :preview-src-list="[scope.row.avatar]"></el-image>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="180">
        <template v-slot="scope">
          <el-button type="primary" plain @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" plain @click="del(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- pagination -->
    <div style="margin: 10px 0">
      <el-pagination @current-change="handleCurrentChange" :current-page="pageNum" :page-size="pageSize"
        layout="total, prev, pager, next" :total="total">
      </el-pagination>
    </div>
    <!-- dialog -->
    <el-dialog v-model="dialogVisible" :title="formTitle" width="30%">
      <el-form :model="form" :rules="rules" ref="formRef">
        <el-form-item label="账号"   prop="username"> <el-input v-model="form.username" placeholder="账号"></el-input>  </el-form-item>
        <el-form-item label="姓名"   prop="name">     <el-input v-model="form.name"     placeholder="姓名"></el-input>  </el-form-item>
        <el-form-item label="电话"   prop="phone">    <el-input v-model="form.phone"    placeholder="电话"></el-input>  </el-form-item>
        <el-form-item label="邮箱"   prop="email">    <el-input v-model="form.email"    placeholder="邮箱"></el-input>  </el-form-item>
        <el-form-item label="地址"   prop="address">  <el-input v-model="form.address"  placeholder="地址"></el-input>  </el-form-item>
        <el-form-item label="头像"   prop="avatar">
          <el-upload class="avatar-uploader" :action="uploadAvatarURL" :headers="uploadHeaders" :file-list="form.avatar ? [form.avatar] : []" list-type="picture" :on-success="handleAvatarUploadSuccess">
            <el-button type="primary">上传头像</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="角色"   prop="role">
          <el-radio-group v-model="form.role"><el-radio label="USER">用户</el-radio><el-radio label="ADMIN">管理员</el-radio></el-radio-group>
        </el-form-item>
      </el-form>
        <!-- dialog footer -->
        <template #footer>
          <div class="dialog-footer">
            <el-button type="info" @click="handleDialogCancel">取消</el-button>
            <el-button type="primary" @click="handleDialogSubmit">提交</el-button>
          </div>
        </template>
    </el-dialog>    
  </div>
</template>

<style lang="scss" scoped>
.content {
  
}
</style>
